package com.lemon.core.ip2region.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.List;

/**
 * 根据ip查询地址
 *
 * @author pan
 * @since 2020-01-16
 */
@Slf4j
public class RegionUtils {
    private RegionUtils() {
    }

    private static final List<String> HOST_IPS = CollUtil.newArrayList("0:0:0:0:0:0:0:1", "127.0.0.1");

    private static Searcher searcher = null;

    static {
        // 1、从 dbPath 加载整个 xdb 到内存。
        ClassPathResource resource = new ClassPathResource("/ip2region/ip2region.xdb");
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] dbBinStr = IoUtil.readBytes(inputStream);
            // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
            searcher = Searcher.newWithBuffer(dbBinStr);
            log.info("init ip region");
        } catch (Exception e) {
            log.error("init ip region error", e);
        }
    }

    /**
     * 解析IP
     *
     * @param ip ip
     * @return 查询结果
     */
    public static String getRegion(String ip) {
        if (HOST_IPS.contains(ip)) {
            return "本机";
        }
        try {
            //db
            if (searcher == null || CharSequenceUtil.isEmpty(ip)) {
                log.error("DbSearcher is null");
                return CharSequenceUtil.EMPTY;
            }
            long startTime = System.currentTimeMillis();
            String region = searcher.search(ip);
            if (region == null) {
                return "未知";
            }
            long endTime = System.currentTimeMillis();
            log.debug("region use time[{}] result[{}]", endTime - startTime, region);
            return region;

        } catch (Exception e) {
            log.error("error:", e);
        }
        return CharSequenceUtil.EMPTY;
    }
}
